//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    user_page:'index',
    hasLogin: true,
    openId: '',
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    dianColor: "#888",
    dianColorCur: "#000",
    bannerInfo: [],
    categoryList: [],
    quality: [],
    imgUrl: '',
    onload:0,
  },

  onLoad: function(options) {
    var that = this;
    that.setData({
      onload: 1,//标记该方法onload执行过
    })
    if (!!options && !!options.trace) {
      wx.setStorageSync('trace', options.trace);
    }
    if(options && options.parent_id){
      wx.setStorageSync('parent_id', options.parent_id);
    }
    if(options.prize_id){
      that.setData({
        _prize_id:options.prize_id
      })
    }
    app.codeLogin().then(function (data) {
      that.setData({
        user_info: data,
        hasLogin: data.nickname?true:false,
      });
      
      that.getInfo(options);
      
      that.jumpMiniAppByBox(options);
      that.getShareConfig();
    });
  },
  onHide:function(){
    this.setData({
      onload:0,
    })
  },
  onUnload:function(){
    this.setData({
      onload:0
    })
  },
  onShow:function(){
    if(wx.getStorageSync('uid') && this.data.onload==0){
      console.log(111);
      var that = this,
        url = 'index/userInfo',
        data = {};
      app.request(url, data, function (res) {
        that.setData({
          bp: res.data.data.user_info.bp,
          tel_fare: res.data.data.user_info.tel_fare,
        })
        if (res.data.data.prize) {
          that.setData({
            showhongbao: true,
            gift_fare: res.data.data.prize
          })
        }
      })
    }
  },
  // 授权事件
  getUserInfoFun:function(e){
    console.log(e);
    if (e.detail.errMsg !== "getUserInfo:ok") {
      return;
    }
    var that = this;
    var iv = e.detail.iv,
      encryptedData = e.detail.encryptedData;
    app.authuorLogin(iv,encryptedData).then(function(data){
      console.log(data);
      if (data.nickname) {
        var hasLogin = true;
      }
      if (data.is_tan == 1) {
        that.setData({
          showhongbao: true,
          gift_fare: { price: data.price }
        })
      }
      that.setData({
        user_info: data.nickname ? data : "",
        hasLogin: hasLogin?hasLogin:false,
      })
    })
  },
  // 表单提交事件
  formSubmit:function(e){
    console.log(e);
  },
  // 跳转充话费
  changeFare:function(){
    wx.navigateTo({
      url: '/pages/fare/changeFare',
    })
  },
  //事件处理函数
  open: function(evt) {
    let that = this;
    var item = evt.currentTarget.dataset.item;
    if (!!item.qr_image) {
      return wx.previewImage({
        urls: [item.qr_image],
      })
    }
    var url = 'Index/add_click_action',
      dataObj = {
        type: item.type,
        typeId: !!item['banner_id'] ? item['banner_id'] : item['game_id'],
        trace: !!wx.getStorageSync('trace') ? wx.getStorageSync('trace') : ''
      };
    app.request(url, dataObj, function(data) {
      var extrad = item.extraData;
      console.log(data);
      var path = data.path;
      if (typeof extrad == "string") {
        extrad = JSON.parse(extrad);
      }
      console.log(item.path.indexOf("?") != -1 ? item.path : 'pages/index/index?' + item.path)
      wx.navigateToMiniProgram({
        appId: item.app_id,
        path: item.path.indexOf("?") != -1 ? item.path : 'pages/index/index?' + item.path,
        extraData: extrad,
        envVersion: 'release',
        success(res) {
          console.log(res);
          // 打开成功
        }
      });
    })
  },
  onShareAppMessage: function (e) {
    var that = this;
    var id = e.from === 'button' ? e.target.id : 1;
    var title, imageUrl;
    console.log(id);
    title = app.shareConfig['' + id].title,
      imageUrl = app.shareConfig['' + id].img_url;

    return {
      title: title,
      path: '/pages/index/index?parent_id=' + wx.getStorageSync('uid'),
      imageUrl: imageUrl,
      success: function (res) {
        if (res.errMsg == 'shareAppMessage:ok' && that.data.tankuangShow) {
          that.setData({
            tankuangShow: false
          })
        }
      },
      fail: function (res) {
        console.log(res);
      }
    }
  },
  // 
  addPage: function (params = {}) {
    var that = this;
    var trace = wx.getStorageSync('trace');
    var url = 'Index/add_page_view',
      dataObj = {
        trace: trace,
      };

    app.request(url, dataObj, function(res) {
      
    })
  },
  jumpMiniAppByBox: function (params = {}) {
      if (!params.trace) {
        return;
      }
      var channelTrace = params.trace.split("_");
      if (channelTrace.length == 3 && channelTrace[0] == 'box') {
        var path = '';
        for (var j in params) {
          if (j != 'trace') {
            path = setUrlParam(path, j, params[j])
          }
        }

        delete params["trace"];

        wx.navigateToMiniProgram({
          appId: channelTrace[2],
          path: "pages/index/index" + path,
          extraData: params,
          envVersion: 'release',
          success(res) {
            console.log(res);
            // 打开成功
          }
        });
      }
  },
  // 请求首页列表信息
  getInfo: function(options) {
    var that = this;
    var url = 'Index/index',
      dataObj = {};
    if(that.data._prize_id){
      dataObj.prize_id=that.data._prize_id;
    }
    app.request(url, dataObj, function(data) {
      console.log(data);
      var qualityArr = data.data.data.quality;
      var categoryListArr = data.data.data.categoryList;
      that.setData({
        prize_list: data.data.data.prize_list,
        bannerInfo: data.data.data.bannerInfo,
        categoryList: categoryListArr,
        quality: qualityArr,
        imgUrl: data.data.data.imgUrl,
        bp: data.data.data.user_info.bp ? data.data.data.user_info.bp : 0,
        tel_fare:data.data.data.user_info.tel_fare,
      })
      // 抽过奖的情况
      if(data.data.data.prize){
        var gift_fare = data.data.data.prize;
        that.setData({
          showhongbao:true,
          gift_fare: gift_fare
        })
        // 没中奖
        if (gift_fare.is_prize==0){
        
          //没中奖直接调用领取的接口，以免下次进来再弹
          var url = 'fare/receive',
            data = {
              id: gift_fare.id,
              prize_id: gift_fare.prize_id,
              is_prize: 0,//中奖了的
            };
          app.request(url,data,function(res){
            console.log(res);
          })
          
        }
      }
      //todo 
      that.addPage(options);
    })
  },
  goFare:function(){
    wx.switchTab({
      url: '/pages/fare/fare',
    })
  },
  // 关闭红包探矿
  close: function () {
    var that = this;
    var user_info = wx.getStorageSync('user_info');
    user_info.is_tan = 0;
    wx.setStorageSync('user_info', user_info);
    this.setData({
      showhongbao: false,
      tel_fare: (Number(that.data.tel_fare) + Number(that.data.gift_fare.price)).toFixed(2),
    })
  },
  // 领取红包
  getFare: function (e) {
    var user_info = wx.getStorageSync('user_info');
    user_info.is_tan = 0;
    wx.setStorageSync('user_info', user_info);
    var that = this ,
      id = e.currentTarget.dataset.id ,
      pid = e.currentTarget.dataset.pid,
      url = 'fare/receive',
      data = {
        id:id ,
        prize_id:pid,
        is_prize:1,//中奖了的
      }
    if(!id || !pid){
      wx.showToast({
        title: '领取成功',
      })
      that.setData({
        tel_fare: (Number(that.data.tel_fare) + Number(that.data.gift_fare.price)).toFixed(2),
        showhongbao: false
      })
      return;
    }
    app.request(url,data,function(res){
      wx.showToast({
        title: '领取成功',
      })
      that.setData({
        tel_fare: Number(that.data.tel_fare) + Number(that.data.gift_fare.price),
        showhongbao:false
      })
    })
  },
  // 查看中奖名单
  recordDetail:function(e){
    var pid = e.currentTarget.dataset.pid ;
    wx.navigateTo({
      url: '/pages/record/detail?prize_id='+pid,
    })
  },
  getShareConfig:function(){
    var that = this,
      url = 'share/getConfig',
      data = {};
    app.request(url,data,function(res){
      app.shareConfig = res.data.data;
    })
  }
})

function setUrlParam(location, name, value) {
  var url = location;
  var splitIndex = url.indexOf("?") + 1;
  var paramStr = url.substr(splitIndex, url.length);

  var newUrl = url.substr(0, splitIndex);

  // - if exist , replace 
  var arr = paramStr.split('&');
  for (var i = 0; i < arr.length; i++) {
    var kv = arr[i].split('=');
    if (kv[0] == name) {
      newUrl += kv[0] + "=" + value;
    } else {
      if (kv[1] != undefined) {
        newUrl += kv[0] + "=" + kv[1];
      }
    }
    if (i != arr.length - 1) {
      newUrl += "&";
    }
  }

  // - if new, add
  if (newUrl.indexOf(name) < 0) {
    newUrl += splitIndex == 0 ? "?" + name + "=" + value : "&" + name + "=" + value;
  }
  return newUrl;
}